<?php

namespace App\Http\Controllers\Api;

use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\Orders;
use App\RechargePackage;
use App\UserBalanceRecord;
use App\UserBooks;
use App\UserInfo;
use App\User;
use App\UserReadingRecord;
use App\UserSpendRecord;
use App\UserVip;
use App\VipRule;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UCenterController extends Controller
{
    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var UserInfo $thisUserInfo */
        $thisUserInfo = UserInfo::whereUserId($user->id)->first();
        if($thisUserInfo){
            $thisUserInfo->photo_url = FileManager::getImgUrl($thisUserInfo->photo_id);

            if($thisUserInfo->sex == 0){
                $thisUserInfo->sex = '保密';
            }elseif($thisUserInfo->sex == 1){
                $thisUserInfo->sex = '男';
            }else{
                $thisUserInfo->sex = '女';
            }
        }

        /** @var UserVip $thisUserVip */
        $thisUserVip = UserVip::whereUserId($user->id)->whereType('global_vip')->first();
        if($thisUserVip && (strtotime($thisUserVip->end_time) >= time() || $thisUserVip->end_time == "0000-00-00 00:00:00")){
            $user->is_vip   = 1;
            $user->vip_info = $thisUserVip;
        }else{
            $user->is_vip   = 0;
            $user->vip_info = null;
        }

        /** @var UserVip $thisClassify */
        $thisClassifyVip = UserVip::whereUserId($user->id)->whereType('classify_vip')->get();
        if(count($thisClassifyVip) > 0){
            foreach($thisClassifyVip as $thisClassify){
                if($thisClassify && (strtotime($thisClassify->end_time) >= time() || $thisClassify->end_time == "0000-00-00 00:00:00")){
                    $thisClassify->is_buy = 1;
                }else{
                    $thisClassify->is_buy = 0;
                }

                $thisClassifyInfo = Classify::whereId($thisClassify->classify_id)->first();
                if($thisClassifyInfo){
                    $thisClassify->classify_info = $thisClassifyInfo;
                }else{
                    $thisClassify->classify_info = null;

                }
            }
        }


        $user->user_info        = $thisUserInfo;
        $user->classify_package = $thisClassifyVip;
        return response()->json(['level' => 'success','message' => '获取成功','data' => $user]);
    }

    /**
     * 获取充值套餐
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRechargePackage(Request $request){
        $rechargePackage = RechargePackage::whereStatus(1)->orderBy('sort','asc')->orderBy('created_at','desc')->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $rechargePackage]);
    }

    /**
     * 获取我的书架
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserBooksList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page = !is_null($request->get('page')) ? $request->get('page') : 0;

        $userBooksInfoIds = UserBooks::whereUserId($user->id)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->pluck('books_info_id');

        /** @var BooksInfo $userBooksInfo */
        $userBooksInfos = BooksInfo::whereIn('id',$userBooksInfoIds)->get();
        if(count($userBooksInfos) > 0){
            foreach($userBooksInfos as $userBooksInfo){
                $userBooksInfo->img_url = FileManager::getImgUrl($userBooksInfo->img_id);

                if($userBooksInfo->is_complete == 0){
                    $userBooksInfo->is_complete = '连载中';
                }else{
                    $userBooksInfo->is_complete = '完结';
                }
            }
        }

        $totalArticleNum = UserBooks::whereUserId($user->id)->count();
        $userBooksInfos->total_article_num = $totalArticleNum;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userBooksInfos]);
    }

    /**
     * 获取用户最近阅读的记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRecentlyReadList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page = !is_null($request->get('page')) ? $request->get('page') : 0;

        /** @var UserReadingRecord $userRead */
        $userReadings = UserReadingRecord::whereUserId($user->id)->get();
        $recentReadingIds = array();
        if(count($userReadings) > 0){
            foreach($userReadings as $userRead){
                $readTime = strtotime($userRead->read_time);
                $newTime = time();
                $expiredTime = $readTime + (7 * 24 * 3600);
                if($expiredTime >= $newTime){
                    array_push($recentReadingIds,$userRead->id);
                }
            }
        }

        /** @var UserReadingRecord $userReading */
        $userReadingRecord = UserReadingRecord::whereIn('id',$recentReadingIds)->offset($page * $limit)->limit($limit)->get();
        if(count($userReadingRecord) > 0){
            foreach($userReadingRecord as $userReading){
                /** @var BooksInfo $thisBooksInfo */
                $thisBooksInfo = BooksInfo::whereId($userReading->books_info_id)->first();
                if($thisBooksInfo){
                    $userReading->books_Info = $thisBooksInfo;
                }else{
                    $userReading->books_Info = null;
                }

                /** @var BooksChapter $thisBooksChapter */
                $thisBooksChapter = BooksChapter::whereId($userReading->books_chapter_id)->first();
                if($thisBooksChapter){
                    $userReading->books_chapter_name = $thisBooksChapter->name;
                }else{
                    $userReading->books_chapter = null;
                }
            }
        }

        $totalArticleNum = UserReadingRecord::whereIn('id',$recentReadingIds)->count();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userReadingRecord,'total_article_num' => $totalArticleNum]);
    }

    /**
     * 获取用户消费记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userSpendRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $type = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : '';
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page = !is_null($request->get('page')) ? $request->get('page') : 0;

        /** @var UserSpendRecord $userSpend */
        $userSpendRecord = UserSpendRecord::whereUserId($user->id)->whereType($type)->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
        if(count($userSpendRecord) > 0){
            foreach($userSpendRecord as $userSpend){
                if($userSpend->type == 'book'){
                    /** @var BooksInfo $thisBooksInfo */
                    $thisBooksInfo = BooksInfo::whereId($userSpend->books_id)->first();
                    if($thisBooksInfo){
                        $userSpend->book_name = $thisBooksInfo->name;
                    }else{
                        $userSpend->book_name = null;
                    }
                }elseif($userSpend->type == 'books_coin'){
                    /** @var RechargePackage $thisRechargePackage */
                    $thisRechargePackage = RechargePackage::whereId($userSpend->recharge_package_id)->first();
                    if($thisRechargePackage){
                        $userSpend->book_name = $thisRechargePackage->books_coin + $thisRechargePackage->gift_books_coin;
                    }else{
                        $userSpend->book_name = 0;
                    }
                }elseif($userSpend->type == 'vip'){
                    /** @var VipRule $thisVipRule */
                    $thisVipRule = VipRule::whereId($userSpend->vip_rule_id)->first();
                    if($thisVipRule){
                        if($thisVipRule->type == 'global_vip'){
                            $userSpend->book_name = '至尊会员' . " " . $thisVipRule->name;
                        }else{
                            /** @var Classify $thisClassify */
                            $thisClassify = Classify::whereId($thisVipRule->classify_id)->first();
                            if($thisClassify){
                                $userSpend->book_name = $thisClassify->name . " " . $thisVipRule->name;
                            }else{
                                $userSpend->book_name = null;
                            }
                        }
                    }else{
                        $userSpend->book_name = null;
                    }
                }elseif($userSpend->type == 'book_chapter'){
                    /** @var BooksChapter $thisBooksChapter */
                    $thisBooksChapter = BooksChapter::whereId($userSpend->books_id)->first();
                    if($thisBooksChapter){
                        $userSpend->book_name = $thisBooksChapter->name;
                    }else{
                        $userSpend->book_name = null;
                    }
                }else{
                    return response()->json(['level' => 'error','message' => '系统错误']);
                }
            }
        }

        $totalArticleNum = UserSpendRecord::whereUserId($user->id)->count();
        $userSpendRecord->total_article_num = $totalArticleNum;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userSpendRecord]);
    }

    /**
     * 获取阅读记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserReadingRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page = !is_null($request->get('page')) ? $request->get('page') : 0;

        /** @var UserReadingRecord $userReading */
        $userReadingRecord = UserReadingRecord::whereUserId($user->id)->orderBy('read_time','desc')->offset($page * $limit)->limit($limit)->get();
        if(count($userReadingRecord) > 0){
            foreach($userReadingRecord as $userReading){
                /** @var BooksInfo $thisBooksInfo */
                $thisBooksInfo = BooksInfo::whereId($userReading->books_info_id)->first();
                if($thisBooksInfo){
                    $userReading->books_Info = $thisBooksInfo;
                }else{
                    $userReading->books_Info = null;
                }

                /** @var BooksChapter $thisBooksChapter */
                $thisBooksChapter = BooksChapter::whereId($userReading->books_chapter_id)->first();
                if($thisBooksChapter){
                    $userReading->books_chapter_name = $thisBooksChapter->name;
                }else{
                    $userReading->books_chapter_name = null;
                }
            }
        }

        $totalArticleNum = UserReadingRecord::whereUserId($user->id)->count();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userReadingRecord,'total_article_num' => $totalArticleNum]);
    }

    /**
     * 删除阅读记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delReadingRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $readRecordId = !is_null($request->get('read_record_id')) ? $request->get('read_record_id') : 0;

        $thisUserReadingRecord = UserReadingRecord::whereId($readRecordId)->first();
        if(!$thisUserReadingRecord)
            return response()->json(['level' => 'error','message' => '该记录不存在']);

        $thisUserReadingRecord->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisUserReadingRecord]);
    }

    public function orderList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $type = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'allOrders';

        if($type == 'book'){
            /** @var Orders $order */
            $orderList = Orders::whereUserId($user->id)->whereType($type)->orderBy('created_at','desc')->get();
            if(count($orderList) > 0){
                foreach($orderList as $order){
                    $thisBooksInfo = BooksInfo::whereId($order->books_id)->first();
                    if($thisBooksInfo){
                        $order->books_info = $thisBooksInfo;
                    }else{
                        $order->books_info = null;
                    }
                }
            }
        }elseif($type == 'books_coin'){
            /** @var Orders $order */
            $orderList = Orders::whereUserId($user->id)->whereType($type)->orderBy('created_at','desc')->get();
            if(count($orderList) > 0){
                foreach($orderList as $order){
                    $thisRechargePackage = RechargePackage::whereId($order->recharge_package_id)->first();
                    if($thisRechargePackage){
                        $order->recharge_package_info = $thisRechargePackage;
                    }else{
                        $order->recharge_package_info = null;
                    }
                }
            }
        }elseif($type == 'vip'){
            /** @var Orders $order */
            $orderList = Orders::whereUserId($user->id)->whereType($type)->orderBy('created_at','desc')->get();
            if(count($orderList) > 0){
                foreach($orderList as $order){
                    $thisVipRule = VipRule::whereId($order->vip_rule_id)->first();
                    if($thisVipRule){
                        $order->vip_rule_info = $thisVipRule;
                    }else{
                        $order->vip_rule_info = null;
                    }
                }
            }
        }elseif($type == 'book_chapter'){
            /** @var Orders $order */
            $orderList = Orders::whereUserId($user->id)->whereType($type)->orderBy('created_at','desc')->get();
            if(count($orderList) > 0){
                foreach($orderList as $order){
                    $thisBooksChapter = BooksChapter::whereId($order->books_id)->first();
                    if($thisBooksChapter){
                        $order->books_chapter_info = $thisBooksChapter;
                    }else{
                        $order->books_chapter_info = null;
                    }
                }
            }
        }else{
            /** @var Orders $order */
            $orderList = Orders::whereUserId($user->id)->orderBy('created_at','desc')->get();
            if(count($orderList) > 0){
                foreach($orderList as $order){
                    $thisBooksInfo = BooksInfo::whereId($order->books_id)->first();
                    if($thisBooksInfo){
                        $order->books_info = $thisBooksInfo;
                    }else{
                        $order->books_info = null;
                    }


                    $thisRechargePackage = RechargePackage::whereId($order->recharge_package_id)->first();
                    if($thisRechargePackage){
                        $order->recharge_package_info = $thisRechargePackage;
                    }else{
                        $order->recharge_package_info = null;
                    }

                    $thisVipRule = VipRule::whereId($order->vip_rule_id)->first();
                    if($thisVipRule){
                        $order->vip_rule_info = $thisVipRule;
                    }else{
                        $order->vip_rule_info = null;
                    }

                    $thisBooksChapter = BooksChapter::whereId($order->books_id)->first();
                    if($thisBooksChapter){
                        $order->books_chapter_info = $thisBooksChapter;
                    }else{
                        $order->books_chapter_info = null;
                    }
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $orderList]);
    }

    public function getUserBalanceDetails(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /** @var UserBalanceRecord $userBalanceRecord */
        $userBalanceRecordList = UserBalanceRecord::whereUserId($user->id)->get();
        if(count($userBalanceRecordList) > 0){
            foreach($userBalanceRecordList as $userBalanceRecord){
                /** @var UserInfo $secondaryUserInfo */
                $secondaryUserInfo = UserInfo::whereUserId($userBalanceRecord->secondary_user_id)->first();
                if($secondaryUserInfo){
                    $userBalanceRecord->secondary_user_nickname  = $secondaryUserInfo->nickname;
                }else{
                    $userBalanceRecord->secondary_user_nickname  = null;
                }

                /** @var UserSpendRecord $thisOrder */
                $thisOrder = UserSpendRecord::whereOrderNum($userBalanceRecord->order_num)->whereUserId($userBalanceRecord->secondary_user_id)->first();
                if($thisOrder){
                    if($thisOrder->type == 'books_coin'){
                        /** @var RechargePackage $thisRechargePackage */
                        $thisRechargePackage = RechargePackage::whereId($thisOrder->recharge_package_id)->first();
                        if($thisRechargePackage){
                            $userBalanceRecord->buy_article_name = "阅读币";
                        }else{
                            $userBalanceRecord->buy_article_name = null;
                        }
                    }elseif($thisOrder->type == 'vip'){
                        /** @var VipRule $thisVipRule */
                        $thisVipRule = VipRule::whereId($thisOrder->vip_rule_id)->first();
                        if($thisVipRule){
                            if($thisVipRule->type == 'global_vip'){
                                $userBalanceRecord->buy_article_name = "至尊会员";
                            }else{
                                /** @var Classify $thisClassify */
                                $thisClassify = Classify::whereId($thisVipRule->classify_id)->first();
                                if($thisClassify){
                                    $userBalanceRecord->buy_article_name = $thisClassify->name;
                                }else{
                                    $userBalanceRecord->buy_article_name = null;
                                }
                            }
                        }else{
                            $userBalanceRecord->buy_article_name = null;
                        }
                    }
                }else{
                    $userBalanceRecord->buy_article_name = null;
                }
            }
        }

        return response()->json(['level' => 'error','message' => '获取成功','data' => $userBalanceRecordList]);
    }

    public function getMyShareImg(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user){
            return redirect(route('Api.Auth.wxLogin'));
        }

        $id = $request->get('id');

        $url = "http://m.luckread.cn?id=".$id;

        //生成分享图片
        $backgroundImgInfo = Image::make(url('images/share.png'));

        $qrCode = new QrCode();
        $qrCode
            ->setText($url)
            ->setSize(250)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        $qrcodeContent = $qrCode->getImage();

        $qrcodeContentImg = Image::make($qrcodeContent);

        $qrcodeContentImg->resize(150,150);
        $backgroundImgInfo->insert($qrcodeContentImg,'top-left',26,760);

        $response = response()->make($backgroundImgInfo->encode('png'));
        $response->header('Content-Type', 'image/png');

        return $response;
    }
}

